package com.lcz.musicplay.activity;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.os.SystemClock;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.WriterException;
import com.lcz.musicplay.R;
import com.lcz.musicplay.adapter.MyAdapter;
import com.lcz.musicplay.config.Constants;
import com.lcz.musicplay.domain.LyricObject;
import com.lcz.musicplay.service.MusicService;
import com.lcz.musicplay.utils.LrcUtil;
import com.lcz.musicplay.utils.MediaUtils;
import com.lcz.musicplay.widge.LyricShow;
import com.lcz.musicplay.widge.ScrollableViewGroup;
import com.lcz.musicplay.zxing.decoding.EncodingHandler;

import java.io.File;
import java.net.URL;
import java.util.Random;
import java.util.TreeMap;

public class MainActivity extends Activity implements View.OnClickListener {

    private TextView tv_play_musicLrc; //歌词
    private TextView tv_play_curduration;//当前播放时长
    private TextView tv_play_totalduration;//歌曲总时长
    private SeekBar sb_play_duration;//进度条
    private ListView lv_musicList;//歌曲列表
    private ScrollableViewGroup main_svg;
    private ImageButton ib_bottom_play;//播放按钮
    private ImageButton ib_bottom_model;//播放模式
    private LyricShow tv_musicLrc;
    private LrcUtil lrcUtil;
    private MainActivity instance;
    private TreeMap<Integer, LyricObject> lrc_map;

    /*头部控件ID数组*/
    private int[] topIDArry = new int[]{R.id.ib_top_play, R.id.ib_top_musicList, R.id.ib_top_musicLrc, R.id.ib_top_volumn};
    private Handler handler = new Handler() {

        private File f;

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constants.MSG_ONPREPARED:
                    int totleDuration = msg.arg1;//总时长
                    int curDuration = msg.arg2; //当前时长
                    tv_play_totalduration.setText(MediaUtils.int2Str(totleDuration));
                    tv_play_curduration.setText(MediaUtils.int2Str(curDuration));
                    sb_play_duration.setMax(totleDuration);
                    sb_play_duration.setProgress(curDuration);
                    if (lrcUtil == null) {
                        lrcUtil = new LrcUtil(instance);
                    }

                    f = MediaUtils.getLrcFile(MediaUtils.musicList.get(MediaUtils.CURPOSION).getTitle(), MediaUtils.musicList.get(MediaUtils.CURPOSION).getArtist());
                    lrcUtil.ReadLRC(f);
                    lrcUtil.RefreshLRC(curDuration);
                    //歌词控件设置歌词列表文本
                    tv_musicLrc.SetTimeLrc(lrcUtil.getLrcList());
                    //歌词滚动
                    tv_musicLrc.SetNowPlayIndex(curDuration);
                    break;
                case Constants.MSG_ONCOMPLETION:
                    //对当前播放模式进行判断执行下一步操作
                    switch (MediaUtils.CURMODLE) {
                        case Constants.MODEL_NORMAL://顺序播放
                            if (MediaUtils.CURPOSION < MediaUtils.musicList.size() - 1) {
                                changeWhite();
                                MediaUtils.CURPOSION++;
                                changeGreen();
                                startService("播放", MediaUtils.musicList.get(MediaUtils.CURPOSION).getPath());
                            }
                            break;
                        case Constants.MODEL_RANDOM://随机播放
                            Random random = new Random();
                            changeWhite();
                            MediaUtils.CURPOSION = random.nextInt(MediaUtils.musicList.size());
                            changeGreen();
                            startService("播放", MediaUtils.musicList.get(MediaUtils.CURPOSION).getPath());
                            break;
                        case Constants.MODEL_SINGLE://单曲循环
                            startService("播放", MediaUtils.musicList.get(MediaUtils.CURPOSION).getPath());
                            break;
                        case Constants.MODEL_REPEAT://重复播放
                            if (MediaUtils.CURPOSION < MediaUtils.musicList.size() - 1) {
                                changeWhite();
                                MediaUtils.CURPOSION++;
                                changeGreen();
                                startService("播放", MediaUtils.musicList.get(MediaUtils.CURPOSION).getPath());
                            } else {
                                changeWhite();
                                MediaUtils.CURPOSION = 0;
                                changeGreen();
                                startService("播放", MediaUtils.musicList.get(MediaUtils.CURPOSION).getPath());
                            }
                            break;

                    }
                    break;
                case 111:
                    sb_volumn.setVisibility(View.GONE);
                    break;

            }
        }
    };
    //    private GoogleApiClient client;
    private SeekBar sb_volumn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        instance = this;
        initView();
        initViewData();
        initListener();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
//        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private void initViewData() {

        //从SD卡读取数据，属于数据库操作，需要开启线程
        new Thread() {
            @Override
            public void run() {
                super.run();
                MediaUtils.initMusicList(MainActivity.this);
            }
        }.start();
        lv_musicList.setAdapter(new MyAdapter(this));
    }

    private void initListener() {
        /*头部控件初始化监听*/
        findViewById(R.id.ib_top_play).setOnClickListener(this);
        findViewById(R.id.ib_top_musicList).setOnClickListener(this);
        findViewById(R.id.ib_top_musicLrc).setOnClickListener(this);
        findViewById(R.id.ib_top_volumn).setOnClickListener(this);
         /*底部控件初始化监听*/
        ib_bottom_model.setOnClickListener(this);
        findViewById(R.id.ib_bottom_last).setOnClickListener(this);
        ib_bottom_play.setOnClickListener(this);
        findViewById(R.id.ib_bottom_next).setOnClickListener(this);
        findViewById(R.id.ib_bottom_musicList).setOnClickListener(this);

        /*当前页面改变时，头部控件触发响应*/
        main_svg.setOnCurrentViewChangedListener(new ScrollableViewGroup.OnCurrentViewChangedListener() {
            @Override
            public void onCurrentViewChanged(View view, int currentview) {
                setTopSelector(topIDArry[currentview]);
            }
        });

        /*歌曲列表选中改变文本颜色*/
        lv_musicList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //之前颜色变为白色
                changeWhite();
                //当前选中位置
                MediaUtils.CURPOSION = position;
                //当前选中位置改变颜色
                changeGreen();
                //通过服务进行播放
                startService("播放", MediaUtils.musicList.get(position).getPath());
                //改变图标
                ib_bottom_play.setImageResource(R.mipmap.appwidget_pause);
            }
        });

        sb_play_duration.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                sb_play_duration.setProgress(seekBar.getProgress());
                startService("进度", seekBar.getProgress());
            }
        });

    }

    /**
     * 头部控件选中效果
     *
     * @param id
     */
    private void setTopSelector(int id) {
        //初始化所以控件原始状态
        findViewById(R.id.ib_top_play).setSelected(false);
        findViewById(R.id.ib_top_musicList).setSelected(false);
        findViewById(R.id.ib_top_musicLrc).setSelected(false);
        findViewById(R.id.ib_top_volumn).setSelected(false);
        //根据id设置为选中
        findViewById(id).setSelected(true);
    }

    /**
     * 初始化控件
     */
    private void initView() {
        /*首页进度条相关控件*/
        tv_play_musicLrc = (TextView) findViewById(R.id.tv_play_musicLrc);
        tv_play_curduration = (TextView) findViewById(R.id.tv_play_curduration);
        tv_play_totalduration = (TextView) findViewById(R.id.tv_play_totalduration);
        sb_play_duration = (SeekBar) findViewById(R.id.sb_play_duration);
        /*歌词控件*/
        tv_musicLrc = (LyricShow) findViewById(R.id.tv_musicLrc);
        /*歌曲列表控件*/
        lv_musicList = (ListView) findViewById(R.id.lv_musicList);
        /*主控件*/
        main_svg = (ScrollableViewGroup) findViewById(R.id.main_svg);

        /*播放器组件*/
        ib_bottom_play = (ImageButton) findViewById(R.id.ib_bottom_play);
        ib_bottom_model = (ImageButton) findViewById(R.id.ib_bottom_model);
        /*音量调节控件*/
        sb_volumn = (SeekBar) findViewById(R.id.sb_volumn);
        /*默认首页*/
        findViewById(R.id.ib_top_play).setSelected(true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_top_play:
                main_svg.setCurrentView(0);
                setTopSelector(R.id.ib_top_play);
                break;
            case R.id.ib_top_musicList:
                main_svg.setCurrentView(1);
                setTopSelector(R.id.ib_top_musicList);
                break;
            case R.id.ib_top_musicLrc:
                main_svg.setCurrentView(2);
                setTopSelector(R.id.ib_top_musicLrc);
                break;
            case R.id.ib_top_volumn:
                sb_volumn.setVisibility(View.VISIBLE);

                final AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
                //获取音乐最大音量值
                int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                sb_volumn.setMax(maxVolume);
                //当前音量
                sb_volumn.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
                sb_volumn.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        //设置音量
                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, seekBar.getProgress(), AudioManager.FLAG_PLAY_SOUND);
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {

                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        SystemClock.sleep(2000);
                        sb_volumn.setVisibility(View.GONE);
                    }
                });
                if (sb_volumn.getVisibility() == View.VISIBLE) {
                    handler.sendEmptyMessageDelayed(111, 2000);
                }
                break;
            case R.id.ib_bottom_model:
                switch (MediaUtils.CURMODLE) {
                    case Constants.MODEL_NORMAL://顺序播放
                        MediaUtils.CURMODLE = Constants.MODEL_RANDOM;
                        ib_bottom_model.setImageResource(R.mipmap.icon_playmode_shuffle);
                        Toast.makeText(MainActivity.this, "随机播放", Toast.LENGTH_SHORT).show();
                        break;
                    case Constants.MODEL_RANDOM://随机播放
                        MediaUtils.CURMODLE = Constants.MODEL_SINGLE;
                        ib_bottom_model.setImageResource(R.mipmap.icon_playmode_single);
                        Toast.makeText(MainActivity.this, "单曲循环", Toast.LENGTH_SHORT).show();
                        break;
                    case Constants.MODEL_SINGLE://单曲循环
                        MediaUtils.CURMODLE = Constants.MODEL_REPEAT;
                        ib_bottom_model.setImageResource(R.mipmap.icon_playmode_repeat);
                        Toast.makeText(MainActivity.this, "重复播放", Toast.LENGTH_SHORT).show();
                        break;
                    case Constants.MODEL_REPEAT://重复播放
                        MediaUtils.CURMODLE = Constants.MODEL_NORMAL;
                        ib_bottom_model.setImageResource(R.mipmap.icon_playmode_normal);
                        Toast.makeText(MainActivity.this, "顺序播放", Toast.LENGTH_SHORT).show();
                        break;
                }
                break;
            case R.id.ib_bottom_last:
                if (MediaUtils.CURPOSION > 0) {
                    changeWhite();
                    MediaUtils.CURPOSION--;
                    changeGreen();
                    //通过服务进行播放
                    startService("播放", MediaUtils.musicList.get(MediaUtils.CURPOSION).getPath());
                    //改变图标
                    ib_bottom_play.setImageResource(R.mipmap.appwidget_pause);
                }
                break;
            case R.id.ib_bottom_play:
                switch (MediaUtils.CURSTATE) {
                    case Constants.STATE_STOP://默认状态为停止
                        //通过服务进行播放
                        startService("播放", MediaUtils.musicList.get(MediaUtils.CURPOSION).getPath());
                        //改变图标
                        ib_bottom_play.setImageResource(R.mipmap.appwidget_pause);
                        break;
                    case Constants.STATE_PLAY://播放状态
                        //通过服务进行播放
                        startService("暂停");
                        //改变图标
                        ib_bottom_play.setImageResource(R.mipmap.img_playback_bt_play);
                        break;
                    case Constants.STATE_PAUSE://暂停状态
                        //通过服务进行播放
                        startService("继续");
                        //改变图标
                        ib_bottom_play.setImageResource(R.mipmap.appwidget_pause);
                        break;
                }

                break;
            case R.id.ib_bottom_next:
                if (MediaUtils.CURPOSION < MediaUtils.musicList.size() - 1) {
                    changeWhite();
                    MediaUtils.CURPOSION++;
                    changeGreen();
                    //通过服务进行播放
                    startService("播放", MediaUtils.musicList.get(MediaUtils.CURPOSION).getPath());
                    //改变图标
                    ib_bottom_play.setImageResource(R.mipmap.appwidget_pause);
                }
                break;
            case R.id.ib_bottom_musicList:
                /*Intent intent = new Intent();
                intent.setClass(MainActivity.this, MipcaActivityCapture.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent, 1);*/
                break;
        }
    }

    private void startService(String option) {
        Intent service = new Intent(this, MusicService.class);
        service.putExtra("option", option);
        service.putExtra("messenger", new Messenger(handler));
        startService(service);
    }

    private void startService(String option, String path) {
        Intent service = new Intent(this, MusicService.class);
        service.putExtra("option", option);
        service.putExtra("messenger", new Messenger(handler));
        service.putExtra("path", path);
        startService(service);
    }

    private void startService(String option, int progerss) {
        Intent service = new Intent(this, MusicService.class);
        service.putExtra("option", option);
        service.putExtra("messenger", new Messenger(handler));
        service.putExtra("progress", progerss);
        startService(service);
    }

    /*白色字体*/
    private void changeWhite() {
        TextView tv = (TextView) lv_musicList.findViewWithTag(MediaUtils.CURPOSION);
        if (tv != null) {
            tv.setTextColor(Color.WHITE);
        }
    }

    /*绿色字体*/
    private void changeGreen() {
        TextView tv = (TextView) lv_musicList.findViewWithTag(MediaUtils.CURPOSION);
        if (tv != null) {
            tv.setTextColor(Color.GREEN);
        }
    }

    /*迷你歌词*/
    public void setMiniLrc(String lrcString) {
        tv_play_musicLrc.setText(lrcString);
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        //1.回到桌面-->跳到桌面-->开启一个桌面隐式意图
        //需要屏蔽super.onBackPressed()
        // 直接开启手机桌面
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
        //2.显示notification
        showNotification();
    }

    private void showNotification() {

        NotificationManager notifManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //PendingIntent点击通知后所跳转的页面
        PendingIntent contentIntent = PendingIntent.getActivity(this, 1, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
        Notification.Builder builder = new Notification.Builder(this)
                .setContentTitle(MediaUtils.musicList.get(MediaUtils.CURPOSION).getTitle())//设置通知栏显示内容
                .setContentText(MediaUtils.musicList.get(MediaUtils.CURPOSION).getArtist())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
                .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示，一般是系统获取到的时间
                .setContentIntent(contentIntent);//设置通知栏点击意图
        Notification notification = builder.build();
        notification.flags = Notification.FLAG_AUTO_CANCEL;//点击通知后通知消失
        notifManager.notify(0, notification);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    //显示扫描到的内容
                    Toast.makeText(this, "扫描结果：" + bundle.getString("result"), Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    public void show() {
        Notification notification = new Notification.Builder(this).setContentTitle("标题")//设置通知标题
                .setContentText("测试内容") //设置通知栏显示内容
//                .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL)) //设置通知栏点击意图
//                .setNumber(number) //设置通知集合的数量
                .setTicker("测试通知来啦") //通知首次出现在通知栏，带上升动画效果的
                .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示，一般是系统获取到的时间
                .setPriority(Notification.PRIORITY_DEFAULT) //设置该通知优先级
                .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
                .setOngoing(false)//ture，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,
                // 用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
                .setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、
                // 最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合
                // Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音
                // requires VIBRATE permission
//                .setSmallIcon(R.drawable.ic_launcher);//设置通知小ICON
                .build();
    }

}
